﻿using AuthExtensions.Auth;
using DependencyInjection.StaticAccessor;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
using AuthExtensions;

namespace MultiTenant.FreeSql
{
    public class AuthToken : IAuthToken
    {
        private AuthConfig JwtConfig
        {
            get
            {

                //var tenant = TenantContext.Tenant;


                //if (tenant != null && tenant.Id > 0)
                //{
                //    var option = new AuthConfig();
                //    option.ValidAudience = tenant.Jwt.Audience; //audience.ToString();
                //    option.SigningKey = tenant.Jwt.Secret;// (string)secret;
                //    option.ValidIssuer = tenant.Jwt.Issuer;// (string)issuer;
                //    if (tenant.Jwt.ExpirationMinutes > 0)
                //    {
                //        option.ExpirationMinutes = tenant.Jwt.ExpirationMinutes;
                //    }
                //    else
                //    {
                //        option.ExpirationMinutes = 30;
                //    }
                //    return option;
                //}
                //else
                //{
                return _authconfig;
                //}

            }
        }
        private IHttpContextAccessor _accessor;
        private readonly ICache _cache;
        private readonly AuthConfig _authconfig;
        public AuthToken(IHttpContextAccessor accessor, IOptions<AuthConfig> authconfig)
        {
            _accessor = accessor;
            _authconfig = authconfig.Value;

        }

        public TokenDto Build(Claim[] claims)
        {
            var tenant = TenantContext.Tenant;
            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(JwtConfig.SigningKey));
            var signingCredentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
            var now = DateTime.Now;
            var token = new JwtSecurityToken(
                issuer: JwtConfig.ValidIssuer,
                audience: JwtConfig.ValidAudience,
                claims: new Claim[] { new Claim("tenant", tenant?.Identifier ?? "main_") }.Concat(claims),
                notBefore: now,
                expires: now.AddMinutes(JwtConfig.ExpirationMinutes),
                signingCredentials: signingCredentials
            );
            return new TokenDto { Token = new JwtSecurityTokenHandler().WriteToken(token), ExpiresIn = now.AddMinutes(JwtConfig.ExpirationMinutes), Now = now };
        }


        /// <summary>
        /// 
        /// </summary>
        /// <param name="claims"></param>
        /// <returns></returns>
        public async Task BuildIdentity(Claim[] claims)
        {
            var identity = new ClaimsIdentity(CookieAuthenticationDefaults.AuthenticationScheme);
            identity.AddClaims(claims);
            await _accessor.HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme,
                new ClaimsPrincipal(identity),
                new AuthenticationProperties
                {
                    ExpiresUtc = DateTime.Now.AddMinutes(JwtConfig.ExpirationMinutes),
                    IsPersistent = true
                });

        }
    }
}
